<template>
  <div class="nav-wrapper">
    <nav 
      ref="navRef"
      :class="['navbar', { 'navbar--hidden': !visible, 'navbar--sticky': isSticky }]"
    >
      <div class="navbar-container">
        <div class="navbar-left">
          <div class="logo" @click="goHome">
            <!-- <span>电商平台</span> -->
             <img src="/src/assets/logo.png" alt="logo" style="width: 190px;"/>
          </div>
          
          <ul class="nav-menu">
            <li 
              class="menu-item"
              :class="{ active: activeMenu === 'home' }"
              @click="changeMenu('home')"
            >
              首页
            </li>
            <li 
              class="menu-item"
              :class="{ active: activeMenu === 'classify' }"
              @click="changeMenu('classify')"
            >
              商品分类
            </li>
            <li 
              class="menu-item"
              :class="{ active: activeMenu === 'flashsale' }"
              @click="changeMenu('flashsale')"
            >
              限时抢购
            </li>
            <li 
              class="menu-item"
              :class="{ active: activeMenu === 'coupons' }"
              @click="changeMenu('coupons')"
            >
              优惠券中心
            </li>
          </ul>
        </div>
        
        <div class="navbar-right">
          <div class="search-box">
            <input 
              type="text" 
              placeholder="搜索商品..." 
              v-model="searchKeyword"
              @keyup.enter="handleSearch"
            />
            <button class="search-btn" @click="handleSearch">
              <el-icon :style="{ fontSize: '24px'}"><Search /></el-icon>
            </button>
          </div>
          
          <!-- 购物车 -->
          <div class="cart-icon" @click="goToCart">
            <el-icon :style="{ fontSize: '30px', marginTop: '10px' }"><ShoppingCart /></el-icon>
            <span class="cart-badge" v-if="cartCount > 0">{{ cartCount }}</span>
          </div>

          <div class="user-section" v-if="!isLoggedIn">
            <span class="login-btn" @click="showLoginModal = true">登录</span>
            <span class="register-btn" @click="showRegisterModal = true">注册</span>
          </div>
          
          <div class="user-avatar" v-else @click="toggleUserMenu">
            <img :src="userAvatar" alt="用户头像" class="avatar-img" />
            <transition name="fade">
              <div class="user-menu" v-show="showUserMenu">
                <div class="menu-item" @click="goToProfile">
                  <svg-icon icon-class="user" />
                  <span>个人中心</span>
                </div>
                <div class="menu-item" @click="goToOrders">
                  <svg-icon icon-class="order" />
                  <span>我的订单</span>
                </div>
                <div class="divider"></div>
                <div class="menu-item" @click="handleLogout">
                  <svg-icon icon-class="logout" />
                  <span>退出登录</span>
                </div>
              </div>
            </transition>
          </div>
        </div>
      </div>
    </nav>

    <!-- 登录模态框 -->
    <LoginModal 
      v-model:visible="showLoginModal"
      @showRegister="showRegisterModal = true"
    />
    
    <!-- 注册模态框 -->
    <RegisterModal 
      v-model:visible="showRegisterModal"
      @showLogin="showLoginModal = true"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
import { useCartStore } from '@/stores/cartStore'
import LoginModal from '@/views/Login.vue'
import RegisterModal from '@/views/Register.vue'
import UserCenter from './UserCenter.vue'

const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

// 导航栏控制相关
const navRef = ref(null)
const visible = ref(true)
const isSticky = ref(false)
const lastScrollPosition = ref(0)
const scrollThreshold = 5 // 滚动阈值，避免微小滚动触发

// 模态框状态
const showLoginModal = ref(false)
const showRegisterModal = ref(false)

// 原来的业务逻辑保持不变
const activeMenu = ref('home')
const searchKeyword = ref('')
const showUserMenu = ref(false)
const isLoggedIn = computed(() => userStore.isLoggedIn)
const userAvatar = computed(() => userStore.userImg || '/src/assets/user.png')
const cartCount = computed(() => cartStore.totalItems)

// 滚动处理函数
const handleScroll = () => {
  const currentScrollPosition = window.pageYOffset || document.documentElement.scrollTop
  
  // 避免微小滚动触发
  if (Math.abs(currentScrollPosition - lastScrollPosition.value) < scrollThreshold) {
    return
  }

  // 向下滚动且超过导航栏高度时隐藏
  if (currentScrollPosition > lastScrollPosition.value && currentScrollPosition > navRef.value.offsetHeight) {
    visible.value = false
  } 
  // 向上滚动时显示
  else if (currentScrollPosition < lastScrollPosition.value) {
    visible.value = true
  }
  
  // 设置粘性状态
  isSticky.value = currentScrollPosition > navRef.value.offsetHeight
  
  lastScrollPosition.value = currentScrollPosition
}

const throttle = (func, limit) => {
  let lastFunc
  let lastRan
  return function() {
    const context = this
    const args = arguments
    if (!lastRan) {
      func.apply(context, args)
      lastRan = Date.now()
    } else {
      clearTimeout(lastFunc)
      lastFunc = setTimeout(function() {
        if ((Date.now() - lastRan) >= limit) {
          func.apply(context, args)
          lastRan = Date.now()
        }
      }, limit - (Date.now() - lastRan))
    }
  }
}

const changeMenu = (menu) => {
  activeMenu.value = menu
  switch(menu) {
    case 'home': router.push('/'); break
    case 'classify': router.push('/classify'); break
    case 'flashsale': router.push('/flashsale'); break
    case 'coupons': router.push('/coupons'); break
  }
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    router.push({
      path: '/search',
      query: { keyword: searchKeyword.value.trim() }
    })
    searchKeyword.value = ''
  }
}

const goHome = () => { router.push('/'); activeMenu.value = 'home' }
const goToCart = () => { router.push('/cart') }  // 购物车
const goToProfile = () => { router.push('/usercenter'); showUserMenu.value = false }  // 个人中心
const goToOrders = () => { router.push('/myorder'); showUserMenu.value = false }  // 我的订单
const toggleUserMenu = () => { showUserMenu.value = !showUserMenu.value }
const handleLogout = () => { 
  userStore.logout(); 
  showUserMenu.value = false; 
  // 登出后不需要跳转到登录页
}

const handleClickOutside = (event) => {
  const userAvatarEl = document.querySelector('.user-avatar')
  if (userAvatarEl && !userAvatarEl.contains(event.target)) {
    showUserMenu.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
  window.addEventListener('scroll', throttle(handleScroll, 100))
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  window.removeEventListener('scroll', throttle(handleScroll, 100))
})
</script>

<style scoped>
.nav-wrapper {
  height: 70px;
}
.navbar {
  width: 100%;
  height: 70px;
  background-color: rgb(254, 248, 236);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.navbar-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.navbar--sticky {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
}

.navbar--hidden {
  transform: translateY(-100%);
}

.navbar-left {
  display: flex;
  align-items: center;
}

.logo {
  font-size: 22px;
  font-weight: bold;
  color: #ff6700;
  margin-right: 30px;
  cursor: pointer;
}

.nav-menu {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
}

.menu-item {
  padding: 0 15px;
  height: 60px;
  line-height: 60px;
  font-size: 16px;
  color: #333;
  cursor: pointer;
  transition: all 0.3s;
}

.menu-item:hover {
  color: #ff6700;
}

.menu-item.active {
  color: #ff6700;
  border-bottom: 2px solid #ff6700;
}

.navbar-right {
  display: flex;
  align-items: center;
}

.search-box {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.search-box input {
  width: 200px;
  height: 36px;
  padding: 0 15px;
  border: 1px solid #eee;
  border-radius: 18px 0 0 18px;
  outline: none;
  transition: all 0.3s;
}

.search-box input:focus {
  border-color: #ff6700;
}

.search-btn {
  width: 40px;
  height: 38px;
  border: none;
  background-color: #ff6700;
  color: white;
  border-radius: 0 18px 18px 0;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-btn:hover {
  background-color: #ff4500;
}

.cart-icon {
  position: relative;
  margin-right: 20px;
  cursor: pointer;
  font-size: 20px;
  color: #666;
  transition: all 0.3s;
}

.cart-icon:hover {
  color: #ff6700;
}

.cart-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: #ff6700;
  color: white;
  border-radius: 50%;
  width: 18px;
  height: 18px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-section {
  display: flex;
  align-items: center;
}

.login-btn, .register-btn {
  margin-left: 15px;
  cursor: pointer;
  color: #666;
  transition: all 0.3s;
}

.login-btn:hover, .register-btn:hover {
  color: #ff6700;
}

.user-avatar {
  position: relative;
  cursor: pointer;
}

.avatar-img {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  object-fit: cover;
}

.user-menu {
  position: absolute;
  right: 0;
  top: 50px;
  width: 150px;
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  padding: 10px 0;
  z-index: 10;
}

.user-menu .menu-item {
  display: flex;
  align-items: center;
  padding: 8px 15px;
  height: auto;
  line-height: normal;
  font-size: 14px;
}

.user-menu .menu-item:hover {
  background-color: #f5f5f5;
}

.user-menu .menu-item svg {
  margin-right: 8px;
  font-size: 16px;
}

.divider {
  height: 1px;
  background-color: #eee;
  margin: 5px 0;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>